package com.zhangqiang.git.auth2secrity.framework.security.service;

import com.zhangqiang.git.auth2secrity.framework.config.OAuth2Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService
{
    @Autowired
    @Lazy
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private OAuth2Config oAuth2Config;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // name 可以是用户名、登录名、手机号 目前先支持手机号 从数据库查询
        if(name==null || "".equals(name) || name.equals(oAuth2Config.getOauth2_userName())){
            throw new UsernameNotFoundException("用户不存在");
        }

        //由于权限参数不能为空，所以这里先使用AuthorityUtils.commaSeparatedStringToAuthorityList方法模拟一个admin的权限，该方法可以将逗号分隔的字符串转换为权限集合。
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
        authorities.add(new SimpleGrantedAuthority("ROLE_admin"));

        return new User(
                name,
                // 因为数据库是明文，所以这里需加密密码
                bCryptPasswordEncoder.encode(oAuth2Config.getOauth2_userPwd()),
                authorities
        );

    }
}
